-- UIArtifactSelect
-- Create by zouyb
-- 神器选择界面

require "game/ui/form/artifact/UIArtifactCompound"
require "game/ui/form/shop/UIUsePuzzles"

-- UIArtifactSelect继承自Layer
UIArtifactSelect = class("UIArtifactSelect", function()
    return cc.Layer:create();
end);

local MAX_GRID_ROW    = 3;
local MAX_GRID_COLUMN = 3;

-- 每页神器的数量
local PAGE_GRID_COUNT = MAX_GRID_ROW*MAX_GRID_COLUMN;

-- 翻页容器的页数
local PAGE_AMOUNT = 3;

-- 一页包裹的宽高
local PAGE_WIDTH  = 500;
local PAGE_HEIGHT = 460;

-- 标签页
local ARTIFACT_TYPE_SELECT  = 1;  -- 神器选择页
local ARTIFACT_TYPE_REPAIR  = 2;  -- 神器维修页
-- local ARTIFACT_TYPE_RELIC   = 3;  -- 遗物

local TAB_TYPE_LIST = {
    ARTIFACT_TYPE_SELECT,       -- 神器选择页
    ARTIFACT_TYPE_REPAIR,       -- 神器维修页
    -- ARTIFACT_TYPE_RELIC,        -- 遗物
};

local riskRelicId = 6000;
local fightRelicId = 6010;
local magicRelicId = 6020;

local artifactPage = {};
function UIArtifactSelect.create()
    return UIArtifactSelect.new();
end

-- 构造函数
function UIArtifactSelect:ctor(id)
    -- 初始化
    self:setName("UIArtifactSelect");
    local node = cc.CSLoader:createNode("layout/artifactt/ArtifactSelect.csb");
    self:addChild(node);
    self.node = node;

    local CT = node:getChildByName("CT");

    self.CT = CT;
    local scrollview = findChildByName(CT, "template/scroll_view");
    self.scrollView = scrollview;
    self.panel = scrollview;
    self.scrollView:setVisible(true);

    -- 角标重置为炼金仓库的
    local leftBg = findChildByName(CT, "template/bg_type");
    local rightBg = findChildByName(CT, "template/bg_type2");
    leftBg:loadTexture(getTitleBgIconPath("alchemy"));
    rightBg:loadTexture(getTitleBgIconPath("alchemy"));

    -- 需要左右翻页显示，显示左右蒙版
    local mask1 = findChildByName(self.node, "CT/template/mask3");
    mask1:setVisible(true);
    local mask2 = findChildByName(self.node, "CT/template/mask4");
    mask2:setVisible(true);

    self.titleList = {[1] = "risk_depart_artifact", [2] = "fight_depart_artifact", [3] = "magic_depart_artifact"}

    -- 初始化当前页面
    self:init();

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 获取三类神器
    self:getDepartmentArtifact();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

function UIArtifactSelect:getTabsTitle()
    -- 标签页标题
    local TAB_NAME_MAP = {
        [ARTIFACT_TYPE_SELECT]   = getLocStr("tab_title_strengthen"),
        [ARTIFACT_TYPE_REPAIR]   = getLocStr("artifact_repair_tab"),
        -- [ARTIFACT_TYPE_RELIC]    = getLocStr("artifact_relic"),
    };

    return TAB_NAME_MAP;
end

-- 初始化标签页
function UIArtifactSelect:init()
    -- 默认选择第一个标签页
    self.operateType = TAB_TYPE_LIST[1];

    local tabNode3  = findChildByName(self.node, "CT/tabs/tab3");
    tabNode3:setVisible(false);

    self.tabs = {};
    for i, operateType in pairs(TAB_TYPE_LIST) do
        local tabNode  = findChildByName(self.node, "CT/tabs/tab"..i);

        table.insert(self.tabs, tabNode);

        -- 绑定当前的类型
        local icon = findChildByName(tabNode, "icon");
        icon.operateType = operateType;
    end
    self:redrawTabs();

    for i = 1, #self.tabs do
        local tab = self.tabs[i];
        tab:setPositionY(tab:getPositionY() + 100);
    end

    local tabNodes = findChildByName(self.node, "CT/tabs");
    tabNodes:setVisible(true);

    -- tab的动画效果
    performWithDelay(self, function() self:playTabEffect(); end, 0.2);
end

-- 重绘标签页
function UIArtifactSelect:redrawTabs()

    for _, tabNode in pairs(self.tabs) do
        local iconImg   = findChildByName(tabNode, "icon");
        local lightImg = findChildByName(tabNode, "light");
        local titleLabel = findChildByName(tabNode, "title");
        local operateType = iconImg.operateType;

        local kerning = 0;

        if not isFullWidthLang() then
            kerning = -4;
        end
        TextStyleM.setOutlineStyle(titleLabel, TextStyleM.TEXT_OUTLINE_SIZE, TextStyleM.TEXT_OUTLINE_COLOR_DARK);
        TextStyleM.setTextStyle(titleLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, kerning);

        local TAB_NAME_MAP = self:getTabsTitle();

        titleLabel:setString(TAB_NAME_MAP[operateType]);
        local normalColor = TextStyleM.TEXT_COLOR_NORMAL;
        local blendColor  = TextStyleM.TEXT_COLOR_BLEND;

        if self.operateType == operateType then
            -- 被选中的标签高亮显示
            lightImg:setVisible(true);
            iconImg:setHighlighted(true);
            iconImg:setTouchEnabled(false);
            iconImg:setColor(normalColor);
            titleLabel:setColor(normalColor);
        else
            lightImg:setVisible(false);
            iconImg:setHighlighted(false);
            iconImg:setTouchEnabled(true);
            iconImg:setColor(blendColor);
            titleLabel:setColor(blendColor);
        end
    end
end

-- 页签动画效果
function UIArtifactSelect:playTabEffect()
    -- 带窗口动画播放结束后，页签从上面往下掉
    for i = 1, #self.tabs do
        local tab = self.tabs[i];
        local pos = cc.p(tab:getPosition());
        local delay = cc.DelayTime:create(0.2 * (i - 1));
        local moveDown = cc.MoveTo:create(0.2, cc.p(pos.x, pos.y - 100 - 5));
        local moveBack = cc.MoveTo:create(0.2, cc.p(pos.x, pos.y - 100));
        local action = cc.Sequence:create(delay, moveDown, moveBack);
        tab:runAction(action);
    end
end

-- 创建3页神器列表
function UIArtifactSelect:initPageGrids()
    -- 图标间距(横向)
    local wGap = 20;

    -- 图标间距(纵向)
    local hGap = 20;

    -- 图标宽度
    local iconWidth = 127;

    -- 图片高度
    local iconHeight = 125;

    local topHGap  = 20;
    local leftWGap = 40;

    local function createOnePage(layout, pageIndex)
        local iconNode = cc.CSLoader:createNode("layout/artifactt/SelectItem.csb");
        local widget = replaceNodeWithWidget(iconNode);

        -- 计算本页起始索引
        local index = 1;
        for row = 1, MAX_GRID_ROW do
            for col = 1, MAX_GRID_COLUMN do

                local child = widget:clone();
                child:setName("artifact" .. index);

                local x = (col - 1) * (iconWidth + wGap) + iconWidth / 2 + leftWGap;
                local y = PAGE_HEIGHT - (row * iconHeight + (row - 1) * hGap)  + iconHeight / 2 - topHGap;

                index = index + 1;

                child:setPositionX(x);
                child:setPositionY(y);

                layout:addChild(child);
            end
        end
    end

    -- 预先创建所有分页
    local panel = self.scrollView;
    for i = 1, PAGE_AMOUNT do
        local layout = ccui.Layout:create();
        layout:setContentSize(panel:getContentSize());

        createOnePage(layout, i);

        panel:addPage(layout);
    end
end

-- 排序
local function sortItem(id1, id2)
    local type1 = EquipM.query(id1, "type");
    local type2 = EquipM.query(id2, "type");

    if type1 > type2 then
        return true;
    else
        return false;
    end
end

-- 获得3类神器
function UIArtifactSelect:getDepartmentArtifact()
    local departments = ArtifactM.getDepartmentIds();
    self.riskerIds = table.deepcopy(departments.risker);
    self.wizardIds = table.deepcopy(departments.wizard);
    self.fighterIds = table.deepcopy(departments.fighter);

    table.sort(self.riskerIds, sortItem);
    table.sort(self.wizardIds, sortItem);
    table.sort(self.fighterIds, sortItem);

    artifactPage = {self.riskerIds, self.fighterIds, self.wizardIds};
end

-- 适配
function UIArtifactSelect:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");

    -- mask居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "mask");
end

-- 重置3类格子
function UIArtifactSelect:resetArtifactGrids()
    for index, ids in pairs(artifactPage) do

        local page = self.panel:getPage(index - 1);
        if page == nil then
            return;
        end

        local title = self.titleList[index];

            -- 显示标题
        local titleLabel = findChildByName(self.CT, "template/title");
        TextStyleM.setTitleStyle(titleLabel);
        titleLabel:setString(getLocStr(title));

        -- 副标题
        local descLabel = findChildByName(self.CT, "template/subhead");
        TextStyleM.setSubheadStyle(descLabel);
        if ARTIFACT_TYPE_SELECT == self.operateType then
            descLabel:setString(getLocStr("strengthen_compound"));
        else
            descLabel:setString(getLocStr("repair_dura"));
        end

        local bgType = index + 2;
        for i = 1, PAGE_GRID_COUNT do
            self:redrawTitleAndBtn();
            local child = page:getChildByName("artifact" .. i);
            local classId = ids[i];
            if child then
                -- 根据当前标签页，初始化格子数据
                if ARTIFACT_TYPE_SELECT == self.operateType then
                    -- 神器强化升级页面
                    self:initSelectItem(child, classId, bgType);

                elseif ARTIFACT_TYPE_REPAIR == self.operateType then
                    self:initRepairItem(child, classId, bgType);
                end
            end
        end
    end
end

-- 重绘页面标题
function UIArtifactSelect:redrawTitleAndBtn()
    -- self:switchNext();
    local curPageIndex = self.panel:getCurPageIndex();
    local title = self.titleList[curPageIndex + 1];
    local titleLabel = findChildByName(self.node, "CT/template/title");
    titleLabel:setString(getLocStr(title));
end

-- 初始化神器强化和合成界面
function UIArtifactSelect:initSelectItem(grid, id, bgType)
    -- 图标
    local iconImg = findChildByName(grid, "icon");
    local fileName = ItemM.query(id, "icon");
    iconImg:loadTexture(getItemIconPath(fileName));

    -- 神器等级
    local levelLabel = findChildByName(grid, "level_label");
    local level = ArtifactM.getArtifactLevel(id);

    local bg = findChildByName(grid, "bg");

    bg:loadTexture(getFrameBgIconPath("rank", 1));

    -- 没有神器等级是-1
    if level >= 0 then
        iconImg:setOpacity(255);
        bg:setOpacity(255);
        levelLabel:setVisible(true);
        if level > 0 then
            TextStyleM.setTextStyle(levelLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
            levelLabel:setString("+" .. tonumber(level));
        end
    else
        iconImg:setOpacity(125);
        bg:setOpacity(125);
        levelLabel:setVisible(false);
    end

    -- 背景图上设置当前神器ID

    --bg:setTitleText("");
    bg.classId = id;

    -- 设置提醒/提示只判断是否自身碎片足够
    local canCompound = ArtifactM.canCompound(id) == true;
    local canUpgrade = ArtifactM.canUpgrade(id, "scarpNeed") == true;

    local hint = findChildByName(grid, "hint");

    if canCompound or canUpgrade then
        hint:setVisible(true);
        playBubbleAnima(hint, false, 0.8);
    else
        hint:stopAllActions();
        hint:setVisible(false);
    end

    -- 注册背景点击事件
    local function onSelectItemClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            local classId = sender.classId;
            closeFormByName("UIEquipTooltip");

            -- 暂离时可能会变化的神器不可操作
            local carryId = ArtifactM.getCarryArtifact() or -1;
            if carryId == classId then
                alert(getLocStr("using_artifact_tip"));
                return;
            end
            local uiItemDesc = UIEquipTooltip.create(classId, "operate");

            UIMgr:getCurrentScene():addForm(uiItemDesc);
            AudioM.playFx("equip_put");
        end
    end
    bg:addTouchEventListener(onSelectItemClick);
end

function UIArtifactSelect:initRepairItem(grid, id, bgType)
     -- 图标
    local iconImg = findChildByName(grid, "icon");
    local fileName = ItemM.query(id, "icon");
    iconImg:loadTexture(getItemIconPath(fileName));

    -- 无用图标隐藏
    local levelLabel = findChildByName(grid, "level_label");
    levelLabel:setVisible(false);
    local hint = findChildByName(grid, "hint");
    hint:stopAllActions();
    hint:setVisible(false);

    -- 神器等级()
    local bg = findChildByName(grid, "bg");
    bg:loadTexture(getFrameBgIconPath("rank", 1));

    local level = ArtifactM.getArtifactLevel(id);

    local sinkerPanel = findChildByName(grid, "star_panel");
    sinkerPanel:removeAllChildren();
    if level >= 0 then
        local durability = ArtifactM.getDurability(id) or 0; -- 剩余耐久度
        local durabilityAll = ArtifactM.query(id, "max_durability") or 0; -- 总耐久度
        local lightStarPath = "images/ui/symbol/point_01.png";
        local darkStarPath = "images/ui/symbol/point_02.png";
        local sinkerLayer = createStarLayerEx(durability, durabilityAll, lightStarPath, darkStarPath, "center", -0.3);

        sinkerPanel:addChild(sinkerLayer);
        iconImg:setOpacity(255);
        bg:setOpacity(255);
    else
        iconImg:setOpacity(125);
        bg:setOpacity(125);
    end

    -- 背景图上设置当前神器ID
    --bg:setTitleText("");
    bg.classId = id;

    local canCompound = ArtifactM.canCompound(id) == true;
    local canUpgrade = ArtifactM.canUpgrade(id) == true;

    local function onRepairItemClick(sender, eventType)
    if eventType == ccui.TouchEventType.ended then
        local classId = sender.classId;

        -- 暂离时可能会变化的神器不可操作
        local carryId = ArtifactM.getCarryArtifact() or -1;
        if carryId == classId then
            alert(getLocStr("using_artifact_tip2"));
            return;
        end

        if ItemM.getAmount(ME.user, classId) < 1 then
            alert(getLocStr("havent_artifact"));
            return;
        end
        local durability = ArtifactM.getDurability(classId) or 0; -- 剩余耐久度
        local durabilityAll = ArtifactM.query(id, "max_durability") or 0; -- 总耐久度
        if durability == durabilityAll then
            alert(getLocStr("not_need_repair"));
            AudioM.playFx("workshop_material");
            return;
        end

         -- 打开神器维修界面
        if UIMgr:getCurrentScene():isOpen("UIArtifactRepair") then
            UIMgr:getCurrentScene():removeForm("UIArtifactRepair");
        end
        local uiArtifactRepair = UIArtifactRepair.create(classId);
        UIMgr.getCurrentScene():addForm(uiArtifactRepair);
        AudioM.playFx("admix_medal");
     end
    end
    bg:addTouchEventListener(onRepairItemClick);
end

-- 显示神器选择界面
function UIArtifactSelect:redraw()
    -- 设置标题样式
    local titleLabel = findChildByName(self.node, "CT/template/title");
    titleLabel:setString(getLocStr("select_artifact_help"));
    TextStyleM.setTitleStyle(titleLabel);

    self.scrollView:removeAllPages();

    local relicNode = findChildByName(self.node, "CT/relic_node");
    relicNode:setVisible(false);
     -- 隐藏当前按钮
    local btnLeft = findChildByName(self.CT, "btn_left");
    btnLeft:setVisible(true);
    local btnRight = findChildByName(self.CT, "btn_right");
    btnRight:setVisible(true);


    -- 根据选中标签页选显示信息
    if self.operateType == ARTIFACT_TYPE_SELECT then
        -- 显示神器列表页
        self:initPageGrids();
        self:resetArtifactGrids();

    elseif self.operateType == ARTIFACT_TYPE_REPAIR then
        -- 显示神器维修页
        self:initPageGrids();
        self:resetArtifactGrids();

    elseif self.operateType == ARTIFACT_TYPE_RELIC then
        -- 显示遗物购买页面
        self:redrawRelic();
    end
end

-- 显示神器详细界面
function UIArtifactSelect:showDetailInfo(id)
    self.isLongPress = true;

    local uiItemDesc = UIEquipTooltip.create(id);
    UIMgr:getCurrentScene():addForm(uiItemDesc);
end

-- 注册商品点击事件
function UIArtifactSelect:registerItemTouchEvent(node)
    -- 注册商品图标点击事件
    local bg = node:getChildByName("bg");
    local function onClick(sender, eventType)
        local id = bg.classId;
        if eventType == ccui.TouchEventType.ended then
            -- 该神器当前等级
            local count = ItemM.getAmount(ME.user, id);
            local level = ArtifactM.getArtifactLevel(id);
            local uiForm;
            if count == 0 then
                -- 打开合成界面
                uiForm = UIArtifactCompound.create(id);
            elseif  level > 8 then
                uiForm = UIArtifactCompound.create(id, 2);
            else
                -- 打开升级界面
                uiForm = UIArtifactUpgrade.create(id);
            end
            UIMgr.getCurrentScene():addForm(uiForm);
            AudioM.playFx("ui_open1");
        end
    end
    bg:addTouchEventListener(onClick);
end

-- 注册事件处理回调函数
function UIArtifactSelect:registerEventCallback()
    -- 关注修复成功的事件
    EventMgr.register("UIArtifactSelect", event.ARTIFACT_UPGRADE, function(args)
        -- 重绘界面
       self:redraw();
        -- elf:jumpTo(args)
        -- self:playUpgradeEffect(args);
    end);

    -- 关注合成事件
    EventMgr.register("UIArtifactSelect", event.ARTIFACT_COMPOUND, function(args)
         -- 重绘界面
         self:redraw();
         --self:jumpTo(args)
    end);

    -- 关注修复成功的事件
    EventMgr.register("UIArtifactSelect", event.ARTIFACT_DURA_RECOVER, function(args)
        -- 重绘界面
        self:redraw();
    end);

    local pageView = findChildByName(self.CT, "template/scroll_view");

        -- 注册翻页事件
    local function pageViewEvent(sender, eventType)
        if eventType == ccui.PageViewEventType.turning then
            self:redrawTitleAndBtn();
        end
    end
    pageView:addEventListener(pageViewEvent)

    -- 使用获得奖励
    EventMgr.register("UIArtifactSelect", event.USE_HERO_RELIC, function(args)
        local bonusList = args.bonusList;
        local classId = args.classId;
        -- 播放获得奖励效果
        self:whenGetBonus(bonusList, classId);
    end);

    EventMgr.register("UIArtifactSelect", event.BUY_HERO_RELIC, function(args)
        self:redraw();
    end);

     -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            EventMgr.removeAll("UIArtifactSelect");


            local uiForm = UIMgr.getCurrentScene():getFormByName("UINewWorkshop");
            if uiForm then
                uiForm:checkArtifactRoom();
                uiForm:showBottomMenu();
            end
        elseif ev == "enter" then
            local uiForm = UIMgr.getCurrentScene():getFormByName("UINewWorkshop");
            if uiForm then
                uiForm:hideBottomMenu();
            end
        end
    end);

end

-- 注册点击事件
function UIArtifactSelect:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIArtifactSelect");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

     -- 注册各个标签页点击事件
    for _, tabNode in pairs(self.tabs) do
        local iconImg = findChildByName(tabNode, "icon");
        local function onTabClick(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                AudioM.playFx("button_spell");
                self.operateType = sender.operateType;

                -- 重绘标签页
                self:redrawTabs();

                -- 重绘页面
                self:redraw();
            end
        end
        iconImg:addTouchEventListener(onTabClick);
    end

    local relicNode = findChildByName(self.node, "CT/relic_node");

     -- 遗物购买按钮
    local btnRisk = findChildByName(relicNode, "btn_risk/btn_buy_relic");
    local function riskBtnClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then

            UIMgr.getCurrentScene():removeFormByName("UIBuyPuzzles");
            local uiform = UIBuyPuzzles.create(riskRelicId, "money", "hero_relic");
            UIMgr.getCurrentScene():addForm(uiform);
            AudioM.playFx("ui_open1");
        end
    end
    btnRisk:addTouchEventListener(riskBtnClick);
    btnRisk:setTitleText("");

    -- 遗物购买按钮
    local btnFight = findChildByName(relicNode, "btn_fight/btn_buy_relic");
    local function fightBtnClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then

            UIMgr.getCurrentScene():removeFormByName("UIBuyPuzzles");
            local uiform = UIBuyPuzzles.create(fightRelicId, "money", "hero_relic");
            UIMgr.getCurrentScene():addForm(uiform);
            AudioM.playFx("ui_open1");
        end
    end
    btnFight:addTouchEventListener(fightBtnClick);
    btnFight:setTitleText("");

    -- 遗物购买按钮
    local btnMagic = findChildByName(relicNode, "btn_magic/btn_buy_relic");
    local function magicBtnClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then

            UIMgr.getCurrentScene():removeFormByName("UIBuyPuzzles");
            local uiform = UIBuyPuzzles.create(magicRelicId, "money", "hero_relic");
            UIMgr.getCurrentScene():addForm(uiform);
            AudioM.playFx("ui_open1");
        end
    end
    btnMagic:addTouchEventListener(magicBtnClick);
    btnMagic:setTitleText("");

    -- 使用遗物功能
    local riskBg = findChildByName(relicNode, "risk_node/bg");
    riskBg:loadTexture("images/ui/frame/rank_large1.png");
    local oriScale = riskBg:getScale();
    local function riskOnClick(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            riskBg:setScale(oriScale - 0.1);
        elseif eventType == ccui.TouchEventType.canceled then
            riskBg:setScale(oriScale);
        elseif eventType == ccui.TouchEventType.ended then
            riskBg:setScale(oriScale);

            UIMgr.getCurrentScene():removeFormByName("UIUsePuzzles");
            local uiform = UIUsePuzzles.create(riskRelicId, "money");
            UIMgr.getCurrentScene():addForm(uiform);
            AudioM.playFx("button_spell");
        end
    end
    riskBg:addTouchEventListener(riskOnClick);

    -- 使用战斗类遗物功能
    local fightBg = findChildByName(relicNode, "fight_node/bg");
    fightBg:loadTexture("images/ui/frame/rank_large1.png");
    local oriScale = fightBg:getScale();
    local function fightOnClick(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            fightBg:setScale(oriScale - 0.1);
        elseif eventType == ccui.TouchEventType.canceled then
            fightBg:setScale(oriScale);
        elseif eventType == ccui.TouchEventType.ended then
            fightBg:setScale(oriScale);

            UIMgr.getCurrentScene():removeFormByName("UIUsePuzzles");
            local uiform = UIUsePuzzles.create(fightRelicId, "money");
            UIMgr.getCurrentScene():addForm(uiform);
            AudioM.playFx("button_spell");
        end
    end
    fightBg:addTouchEventListener(fightOnClick);

    -- 使用魔法类遗物
    local magicBg = findChildByName(relicNode, "magic_node/bg");
    magicBg:loadTexture("images/ui/frame/rank_large1.png");
    local oriScale = magicBg:getScale();
    local function magicOnClick(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            magicBg:setScale(oriScale - 0.1);
        elseif eventType == ccui.TouchEventType.canceled then
            magicBg:setScale(oriScale);
        elseif eventType == ccui.TouchEventType.ended then
            magicBg:setScale(oriScale);

            UIMgr.getCurrentScene():removeFormByName("UIUsePuzzles");
            local uiform = UIUsePuzzles.create(magicRelicId, "money");
            UIMgr.getCurrentScene():addForm(uiform);
            AudioM.playFx("button_spell");
        end
    end
    magicBg:addTouchEventListener(magicOnClick);

    self:registerSwitchBtn();
end

-- 播放升级光效
function UIArtifactSelect:playUpgradeEffect(id)
    local index = table.indexOf(self.ids, id);
    local grid = self.scrollView:getChildByName("item" .. index);

    local lightNode2 = findChildByName(grid, "bg");
    local function playWaiting()
        lightNode2:removeAllChildren();
        playEffect(lightNode2, 1180, 80, 85);
    end
    for i = 1, 2 do
        local delay = i-1;
        performWithDelay(lightNode2, playWaiting, delay);
    end
end

-- 移动中心
function UIArtifactSelect:jumpTo(id)
    local index = table.indexOf(self.ids, id["classId"]);

    local scrollview = findChildByName(self.node, "CT/scrollview");
    local percent = index * 100 / (#self.ids);
    if percent < 0 then
        percent = 0;
    end

    self.scrollView:jumpToPercentVertical(100 - percent);
end


function UIArtifactSelect:switchNext()
    local allPage = self.panel:getPages();
    local btnPrevious = findChildByName(self.CT, "btn_left");
    local btnNext = findChildByName(self.CT, "btn_right");
    if self.panel:getCurPageIndex() == 0 then
        btnPrevious:setVisible(false);
    else
        btnPrevious:setVisible(true);
    end

    if #allPage <= 1 then
        btnNext:setVisible(false);
        btnPrevious:setVisible(false);
    elseif #allPage - 1 == self.panel:getCurPageIndex() then
       btnNext:setVisible(false);
    else
        btnNext:setVisible(true);
    end
end

-- 翻页
function switchPage(self, pageView, toPageIndex)
    pageView:scrollToPage(toPageIndex);
end

--
function UIArtifactSelect:registerSwitchBtn()
 -- 注册'上一页'按钮点击事件
    local btnPrevious = findChildByName(self.CT, "btn_left_panel");
    local function onPreviousClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_tiny");
            local curPageIndex = self.panel:getCurPageIndex();
            if curPageIndex <= 0 then
                -- 已经是第一页，不处理
                switchPage(self, self.panel, 2);
                return;
            end

            -- 切换至上一页
            switchPage(self, self.panel, curPageIndex - 1);
            self:redrawTitleAndBtn();

        end
    end
    btnPrevious:addTouchEventListener(onPreviousClick);

    -- 注册'下一页'按钮点击事件
    local btnNext = findChildByName(self.CT, "btn_right_panel");
    local function onNextClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_tiny");

            local allPage = self.panel:getPages();
            local total = #allPage
            local curPageIndex = self.panel:getCurPageIndex();
            if curPageIndex >= total - 1 then
                switchPage(self, self.panel, 0);
                return;
            end

            -- 切换至上一页
            switchPage(self, self.panel, curPageIndex + 1);
            self:redrawTitleAndBtn();
        end
    end
    btnNext:addTouchEventListener(onNextClick);
end

-- 重绘遗物页面
function UIArtifactSelect:redrawRelic()
    -- 显示标题
    local titleLabel = findChildByName(self.CT, "template/title");
    TextStyleM.setTitleStyle(titleLabel);
    titleLabel:setString(getLocStr("hero_relic"));

    -- 副标题
    local descLabel = findChildByName(self.CT, "template/subhead");
    TextStyleM.setSubheadStyle(descLabel);
    descLabel:setString(getLocStr("click_can_use_tip"));

    -- 隐藏当前按钮
    local btnLeft = findChildByName(self.CT, "btn_left");
    btnLeft:setVisible(false);
    local btnRight = findChildByName(self.CT, "btn_right");
    btnRight:setVisible(false);

    local relicNode = findChildByName(self.node, "CT/relic_node");
    relicNode:setVisible(true);

    -- 当前拥有到时金币
    local moneyCount = ME.user:queryAttrib("money");

    -- 冒险系文本
    local btnRisk = findChildByName(relicNode, "btn_risk");
    local riskNameLabel = findChildByName(btnRisk, "name_label");
    TextStyleM.setTextStyle(riskNameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, getLocKerning() - 4);
    riskNameLabel:setString(getLocStr("btn_text_risk_relic"));
    btnRiskBuy = findChildByName(btnRisk, "btn_buy_relic");
    btnRiskBuy:setTitleText("");

    -- 获得花费
    -- 获得当前出售的价格
    local sellPrice = ItemM.query(riskRelicId, "sell_price");
    local value = sellPrice[1];

    local cost  = value[3];

    local costMoneyLabel = findChildByName(btnRisk, "price_label");
    TextStyleM.setTextStyle(costMoneyLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, getLocKerning() - 2);
    costMoneyLabel:setString(cost);

    -- 战斗系
    local btnFight = findChildByName(relicNode, "btn_fight");
    local fightNameLabel = findChildByName(btnFight, "name_label");
    TextStyleM.setTextStyle(fightNameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, getLocKerning() - 4);
    fightNameLabel:setString(getLocStr("btn_text_fight_relic"));
    btnFightBuy = findChildByName(btnFight, "btn_buy_relic");
    btnFightBuy:setTitleText("");

    local fightsellPrice = ItemM.query(fightRelicId, "sell_price");
    local fightValue = fightsellPrice[1];

    local fightCost  = fightValue[3];
    local fightLabel = findChildByName(btnFight, "price_label");
    TextStyleM.setTextStyle(fightLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, getLocKerning() - 2);
    fightLabel:setString(fightCost);

    -- 魔法系
    local btnMagic = findChildByName(relicNode, "btn_magic");
    local magicNameLabel = findChildByName(btnMagic, "name_label");
    TextStyleM.setTextStyle(magicNameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, getLocKerning() - 4);
    magicNameLabel:setString(getLocStr("btn_text_magic_relic"));
    btnMagicBuy = findChildByName(btnMagic, "btn_buy_relic");
    btnMagicBuy:setTitleText("");

    local magicsellPrice = ItemM.query(magicRelicId, "sell_price");
    local magicValue = magicsellPrice[1];
    local magicCost  = magicValue[3];
    local magicMoneyLabel = findChildByName(btnMagic, "price_label");
    TextStyleM.setTextStyle(magicMoneyLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, getLocKerning() - 2);
    magicMoneyLabel:setString(magicCost);

    --重绘三种遗物
    local riskNode = findChildByName(relicNode, "risk_node");
    local fightNode = findChildByName(relicNode, "fight_node");
    local magicNode = findChildByName(relicNode, "magic_node");

     -- 绘制图标
    local riskIcon = findChildByName(riskNode, "icon");
    riskIcon:loadTexture(getItemIconPath(ItemM.query(riskRelicId, "icon")));

    local figtIcon = findChildByName(fightNode, "icon");
    figtIcon:loadTexture(getItemIconPath(ItemM.query(fightRelicId, "icon")));

    local magicIcon = findChildByName(magicNode, "icon");
    magicIcon:loadTexture(getItemIconPath(ItemM.query(magicRelicId, "icon")));

    local riskBg = findChildByName(riskNode, "bg");
    local fightBg = findChildByName(fightNode, "bg");
    local magicBg = findChildByName(magicNode, "bg");

    local riskAmount = ItemM.getAmount(ME.user, riskRelicId);
    local riskNumLabel = findChildByName(riskNode, "num_label");
    local riskIcon = findChildByName(riskNode, "icon");
    if  riskAmount <= 0 then
        riskBg:setOpacity(127);
        riskIcon:setOpacity(127);
        riskNumLabel:setVisible(false);
    else
        riskBg:setOpacity(255);
        riskIcon:setOpacity(255);
        TextStyleM.setTextStyle(riskNumLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
        riskNumLabel:setString(riskAmount);
        riskNumLabel:setVisible(true);
    end

    local fightAmount = ItemM.getAmount(ME.user, fightRelicId);
    local fightNumLabel = findChildByName(fightNode, "num_label");
    if  fightAmount <= 0 then
        fightBg:setOpacity(127);
        figtIcon:setOpacity(127);
        fightNumLabel:setVisible(false);
    else
        fightBg:setOpacity(255);
        figtIcon:setOpacity(255);
        TextStyleM.setTextStyle(fightNumLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
        fightNumLabel:setString(fightAmount);
        fightNumLabel:setVisible(true);
    end

    local magicAmount = ItemM.getAmount(ME.user, magicRelicId);
    local magicNumLabel = findChildByName(magicNode, "num_label");
    if  magicAmount <= 0 then
        magicBg:setOpacity(127);
        magicIcon:setOpacity(127);
        magicNumLabel:setVisible(false);
    else
        magicBg:setOpacity(255);
        magicIcon:setOpacity(255);
        TextStyleM.setTextStyle(magicNumLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
        magicNumLabel:setString(magicAmount);
        magicNumLabel:setVisible(true);
    end

    -- 记录一下
    self.scrollingData = {
        ["lastAmountRisk"] = riskAmount,
        ["lastAmountFight"] = fightAmount,
        ["lastAmountMagic"] = magicAmount,
    };
end

function UIArtifactSelect:setDisabled(sender)
    sender:setTouchEnabled(false);
    sender:setBright(false);
end

-- 播放获得奖励效果
function UIArtifactSelect:whenGetBonus(bonusList, relicId)
    local i = 1;
    local posNode;
    local gridNode;
    local childList = {};
    local relicNode = findChildByName(self.node, "CT/relic_node");

    if riskRelicId == relicId then
        posNode = findChildByName(relicNode, "risk_node/pos_node");
        gridNode = findChildByName(relicNode, "risk_node");
    elseif fightRelicId == relicId then
        posNode = findChildByName(relicNode, "fight_node/pos_node");
        gridNode = findChildByName(relicNode, "fight_node");
    else
        posNode = findChildByName(relicNode, "magic_node/pos_node");
        gridNode = findChildByName(relicNode, "magic_node");
    end

    -- 标记正在播放光效，屏蔽部分按钮点击
    self.playEffect = true;
    -- 加蒙版，不让点击
    local mask = findChildByName(self.node, "mask");
    mask:setVisible(true);
    mask:setOpacity(0);

    -- 物品光效
    local function callback()
        playEffect(gridNode, 1180, 18, -28,  nil, 0.9);
    end
    performWithDelay(self, callback, 0.3);

    local fightNode = findChildByName(relicNode, "fight_node");
    local riskNode = findChildByName(relicNode, "risk_node");
    local magicNode = findChildByName(relicNode, "magic_node");
    local riskNumLabel = findChildByName(riskNode, "num_label");
    local fightNumLabel = findChildByName(fightNode, "num_label");
    local magicNumLabel = findChildByName(magicNode, "num_label");
    local normalBoxId = FormulaM.invoke("CALC_PUZZLE_BOX_COST_CLASS_ID", "normal");
    local gemBoxId = FormulaM.invoke("CALC_PUZZLE_BOX_COST_CLASS_ID", "gem");
    local riskIcon = findChildByName(riskNode, "icon");
    local fightIcon = findChildByName(fightNode, "icon");
    local magicIcon = findChildByName(magicNode, "icon");

    -- 先停止滚动
    if self.scrollingData then
        stopScrolling(riskNumLabel);
        stopScrolling(fightNumLabel);
        stopScrolling(magicNumLabel);
    end

    -- 当前拥有的数量
    local curRiskNum = ItemM.getAmount(ME.user, riskRelicId);
    local curFightNum = ItemM.getAmount(ME.user, fightRelicId);
    local curMagicNum = ItemM.getAmount(ME.user, magicRelicId);
    local scrollingData = self.scrollingData;

    -- 没有滚动过
    if not scrollingData then
        riskNumLabel:setString(curRiskNum);
        fightNumLabel:setString(curFightNum);
        magicNumLabel:setString(curMagicNum);
        self.scrollingData = {
            ["lastAmountRisk"] = curRiskNum,
            ["lastAmountFight"] = curFightNum,
            ["lastAmountMagic"] = curMagicNum,
        };
    else
        -- 滚动
        local function doneCallback()
            if curRiskNum == 0 then
                riskNumLabel:setVisible(false);
            end
            if curFightNum == 0 then
                fightNumLabel:setVisible(false);
            end
            if curMagicNum == 0 then
                magicNumLabel:setVisible(false);
            end
        end

        numScrollingDown(riskNumLabel, "%d", scrollingData.lastAmountRisk, curRiskNum, 30, nil, doneCallback);
        numScrollingDown(fightNumLabel, "%d", scrollingData.lastAmountFight, curFightNum, 30, nil, doneCallback);
        numScrollingDown(magicNumLabel, "%d", scrollingData.lastAmountMagic, curMagicNum, 30, nil, doneCallback);
        self.scrollingData = {
            ["lastAmountRisk"] = curRiskNum,
            ["lastAmountFight"] = curFightNum,
            ["lastAmountMagic"] = curMagicNum,
        };
    end

    -- 碎片光效
    for _, bonus in pairs(bonusList) do
        -- 物品图标
        local icon = ItemM.query(bonus[2], "icon");
        local image = ccui.ImageView:create(getItemIconPath(icon));
        local posNum = i % 5;
        if posNum == 0 then
            posNum = 5;
        end
        local pos = findChildByName(posNode, "pos".. posNum);
        local pos1 = findChildByName(posNode, "pos1");
        local oriScale = image:getScale();
        image:setScale(0.1);
        image:setVisible(false);
        image:setPosition(cc.p(pos1:getPosition()));
        local function callback()
            image:setVisible(true);
            local moveTo = cc.MoveTo:create(0.6, cc.p(pos:getPosition()));
            local scaleUp = cc.ScaleTo:create(0.6, oriScale * 1.0);
            local fadeOut = cc.FadeOut:create(0.6);
            image:runAction(scaleUp);
            image:runAction(fadeOut);
            image:runAction(moveTo);
        end
        posNode:addChild(image);
        table.insert(childList, image);
        performWithDelay(self, callback, i * 0.15);
        i = i + 1;
    end

    -- 关闭奖励界面后的回调
    local function closeCallBack()
        local classId = relicId;
        if self.removeAlready then
            -- 防止崩溃这里需要处理一下
            return;
        end
        UIMgr.getCurrentScene():removeFormByName("UIUsePuzzles");
        local uiform = UIUsePuzzles.create(classId, "money");
        UIMgr.getCurrentScene():addForm(uiform);
        self:redraw();

        -- 动画播放结束
        self.playEffect = false;

        -- 去掉蒙版
        local mask = findChildByName(self.node, "mask");
        mask:setVisible(false);
    end

    local function delay()
        local pos1 = findChildByName(posNode, "pos1");
        pos1:removeAllChildren();
        for i = 1, #childList do
            posNode:removeChild(childList[i]);
        end
        childList = {};

        local classId = relicId;

        -- 播放物品获得奖励提示
        showBonusNotifyForm(ItemM.query(classId, "name"), bonusList, nil, nil, getLocStr("btn_text_ok"), nil, nil, closeCallBack);
    end
    performWithDelay(self, delay, #bonusList * 0.15 + 1.0);
end